package com.teufandsub.socialproximity.gui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;

import com.teufandsub.socialproximity.R;
import com.teufandsub.socialproximity.controller.Constants;
import com.teufandsub.socialproximity.controller.Controller;
import com.teufandsub.socialproximity.controller.Utils;
import com.teufandsub.socialproximity.logic.User;

/**
 * @author Bastien Mathias <bastienmathias@gmail.com>
 * @author Antoine Teuf <antoine.teuf@gmail.com>
 * @version 1.0
 * @since 2013-05-22
 * 
 * Class to manage your friends : blacklisted people, speak with friends,...
 */

public class FriendListActivity extends SocialProxActivity {

	private ListView friendList_lv,blackList_lv,waitingList_lv;
	private MyListAdapter friendList_adapter,blackList_adapter,waitingList_adapter;
	private ArrayList<User> friendList_al, blackList_al, waitingList_al;
	private static boolean isLaunched=false;
	private static FriendListActivity instance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_friend_list);
		controller = Controller.getInstance();
		instance = this;
		
		TabHost tabs = (TabHost) findViewById(R.id.tabhost);
		tabs.setup();
		
        TabHost.TabSpec spec = tabs.newTabSpec("tag1");
        spec.setContent(R.id.friendlist_lv);
        spec.setIndicator(getResources().getString(R.string.friendlist));
        tabs.addTab(spec);

        spec = tabs.newTabSpec("tag2");
        spec.setContent(R.id.blacklist_lv);
        spec.setIndicator(getResources().getString(R.string.blacklist));
        tabs.addTab(spec);
        
        spec = tabs.newTabSpec("tag3");
        spec.setContent(R.id.waitinglist_lv);
        spec.setIndicator(getResources().getString(R.string.waitinglist));
        tabs.addTab(spec);

        tabs.setCurrentTab(0);
		
        blackList_lv = (ListView) findViewById(R.id.blacklist_lv);    
		friendList_lv = (ListView) findViewById(R.id.friendlist_lv);
		waitingList_lv = (ListView) findViewById(R.id.waitinglist_lv);
	}
	
	/**
	 * This method return the instance of this class since it's a Singleton.
	 *
	 * @return FriendListActivity return instance of this class.
	 */
	public static FriendListActivity getInstance(){
		return instance;
	}
	
	@Override
	protected void onResume() {
		super.onResume();	
		if(!isLaunched){
			AsyncTask<Void, Void, JSONObject> task = new AsyncTask<Void, Void, JSONObject>() {
				ProgressDialog dialog;
				
				protected void onPreExecute() {
					isLaunched=true;
					dialog = ProgressDialog.show(FriendListActivity.this, "", getResources().getString(R.string.loading), true);
				};
				
				@Override
				protected JSONObject doInBackground(Void... params) {
					return controller.getLists(FriendListActivity.this);
				}
				
				protected void onPostExecute(JSONObject result) {
					dialog.dismiss();
					int code=Constants.CODE_ERROR;
					
					try {
						code = result.getInt(Constants.CODE_NAME);
					} catch (Exception e) {
						Log.e(Constants.APP_NAME,"Error to retrieve code of friendlist : " + e.toString());
					}
					
					switch(code){
						case Constants.CODE_ERROR :
							Toast.makeText(FriendListActivity.this, getResources().getString(R.string.error)
									, Toast.LENGTH_LONG).show();
							break;
						case Constants.CODE_REQUESTVALID :
							JSONArray fl = new JSONArray();
							JSONArray bl = new JSONArray();
							JSONArray wl = new JSONArray();
							try {
								fl = result.getJSONArray(Constants.FRIENDLIST_NAME);
								bl = result.getJSONArray(Constants.BLACKLIST_NAME);
								wl = result.getJSONArray(Constants.WAITINGLIST_NAME);
							} catch (Exception e) {
								Log.e(Constants.APP_NAME, "Error to retrieve friend/black list");
							}
							
							friendList_al = toArrayList(fl);
							blackList_al = toArrayList(bl);
							waitingList_al = toArrayList(wl);
							
							friendList_adapter = new MyListAdapter(FriendListActivity.this, friendList_al,MyListAdapter.FRIENDLIST);
							blackList_adapter = new MyListAdapter(FriendListActivity.this, blackList_al ,MyListAdapter.BLACKLIST);
							waitingList_adapter = new MyListAdapter(FriendListActivity.this, waitingList_al,MyListAdapter.WAITINGLIST);
							
							friendList_lv.setAdapter(friendList_adapter);
							blackList_lv.setAdapter(blackList_adapter);
							waitingList_lv.setAdapter(waitingList_adapter);
							break;
						case Constants.CODE_SESSION_INVALID:
							Toast.makeText(FriendListActivity.this, getResources().getString(R.string.invalid_session)
									, Toast.LENGTH_LONG).show();
							Intent i = new Intent(FriendListActivity.this, LoginActivity.class);
							startActivity(i);
							break;
					}
					isLaunched=false;
				};
			};
			
			if(Utils.hasConnectivity(this)){
				task.execute();
			}else{
				Toast.makeText(this, getResources().getString(R.string.no_connectivity), Toast.LENGTH_LONG).show();
			}
		}
	}
	
	/**
	 * Method to convert a list of User as an {@link JSONObject} to an ArrayList
	 * 
	 * @param list {@link JSONArray} The JSONArray you want to convert as a list.
	 * @return {@link ArrayList<User} The Arraylist version of your JSONObject.
	 */
	private ArrayList<User> toArrayList(JSONArray list){
		ArrayList<User> temp = new ArrayList<User>();
		for(int i=0;i<list.length();i++){
			try {
				temp.add(new User(list.getJSONObject(i)));
			} catch (Exception e) {
				Log.e(Constants.APP_NAME,"Error to convert JsonArray to Arraylist");
			}	
		}
		return temp;
	}
	
	/**
	 * Method to update view after a remove of a Friend
	 * 
	 * @param user User to remove
	 */
	public void removeFriend(User user){
		friendList_al.remove(user);
		friendList_adapter.notifyDataSetChanged();
	}
	
	/**
	 * Method to update view after an add of a Friend
	 * 
	 * @param user User you want to add
	 */
	public void addFriend(User user){
		waitingList_al.remove(user);
		if(!friendList_al.contains(user)){
			friendList_al.add(user);
		}
		friendList_adapter.notifyDataSetChanged();
		waitingList_adapter.notifyDataSetChanged();
	}
	
	/**
	 * Method to update the view after the remove of a blacklisted user.
	 * 
	 * @param user User you want to remove of your blacklist
	 */
	public void removeFromBlackList(User user){
		blackList_al.remove(user);
		blackList_adapter.notifyDataSetChanged();
	}
	
	/**
	 * Method to update the view after refuse a friendship asking.
	 * 
	 * @param user User you want to refuse the friendship asking.
	 */
	public void refusedFriendship(User user){
		waitingList_al.remove(user);
		waitingList_adapter.notifyDataSetChanged();
	}
	
}
